<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@page import="java.io.File"%>
<%@page import="com.yuxin.common.util.ObjectUtils"%>
<%@page import="com.yuxin.core.TransactionManager"%>
<%@page import="java.util.HashMap"%>
<%@page import="com.yuxin.common.util.MD5Util"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.Set"%>
<%@page import="java.util.Map"%>
<%@page import="com.yuxin.common.util.FileUploadUtil"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.List"%>
<%@page import="com.yuxin.common.util.DBUtil"%>
<%@page import="java.sql.Connection"%>
<%@page import="com.yuxin.common.util.UUIDUtil"%>

<%
	String action = request.getParameter("action"); // Request action parameter
	Connection conn = null;
	TransactionManager tranM = null;
	String redirect = null;
	try {
		if("register".equals(action)) {	
			conn = DBUtil.getConnection();
			tranM = new TransactionManager(conn);
			tranM.begin();
			
			String userId = UUIDUtil.getUUID();
			String traderId = UUIDUtil.getUUID();
			String sql = "insert into p_user(ID, SRC_ID, USERNAME, PASSWORD, TYPE, CREATE_TIME, UPDATE_TIME) values(?, ?, ?, ?, ?, ?, ?)";
			String sql2 = "insert into p_trade(ID, NAME, LICENSE_IMG, LEGAL_IMG, CONTACT, PHONE, STATUS, CREATE_TIME) values(?, ?, ?, ?, ?, ?, ?, ?)";					
			
			Map map =  FileUploadUtil.upload(request);
			Set set = map.entrySet();
			Iterator iter = set.iterator();
			String licenseFile = "";
			String legalFile = "";
			Map<String, Object> formDataMap = null;
			while(iter.hasNext()) {
				Map.Entry entry = (Map.Entry) iter.next();
			    String key = entry.getKey().toString();
			    Object value = entry.getValue();
				if("files".equals(key)) {
					List<Map<String, Object>> uploadInfoList = (ArrayList<Map<String, Object>>)value; 	
					for(Map mapV : uploadInfoList) {
						String filed = mapV.get("filed").toString();
						if("licenseFile".equals(filed)) {
							licenseFile = mapV.get("path").toString();
						} 
						if("legalFile".equals(filed)) {
							legalFile = mapV.get("path").toString();
						}
					}
				}
				if("formData".equals(key)) {
					formDataMap = (HashMap<String, Object>)value;
				}
			}
			
			String username = formDataMap.get("username").toString();
			String password = formDataMap.get("password").toString();
			
			String name = formDataMap.get("name").toString();
			String contact = formDataMap.get("contact").toString();
			String phone = formDataMap.get("phone").toString();
			
			
			// Check username is not unique
			String sql3 = "select t.ID from p_user t where LOWER(t.USERNAME) = ?";			
			List list = DBUtil.queryList(conn, sql3, username.toLowerCase());
			if(list != null && list.size() > 0) {
				redirect = request.getContextPath()+"/register.jsp?username=" + username + "&errcode=101";
				// delete file
				String realpath = request.getSession().getServletContext().getRealPath("");
				File file = new File(realpath + licenseFile.replace("/", File.separator));
				if(file.exists() && file.isFile()) {
					file.delete();
				}
				file = new File(realpath + legalFile.replace("/", File.separator));
				if(file.exists() && file.isFile()) {
					file.delete();
				}
				return;
			}
			
			int res = DBUtil.executeSql(conn, sql, new Object[]{userId, traderId, username, MD5Util.encodePassword(username+password), 2, new Date(), new Date()});						
			if(res > 0) {
				DBUtil.executeSql(conn, sql2, new Object[]{traderId, name, licenseFile, legalFile, contact, phone, 1, new Date() });
			}
			redirect = request.getContextPath()+"/register_success.jsp";
		}
	} catch (Exception ex) {
		redirect = request.getContextPath()+"/register_fail.jsp";
		tranM.rollback();
		ex.printStackTrace();
	} finally {
		if(tranM != null) {
			tranM.commit();
		}	
		DBUtil.close(conn);	
		response.sendRedirect(redirect);
	}
%>